package com.sapuo.enroll.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc   使用token验证用户是否登录
 * @author zm
 **/
@Component
public class JwtUtil {
    //设置过期时间
    private static final long EXPIRE_DATE=30*60*100000;
    //token秘钥
    private static final String TOKEN_SECRET = "7223a002ee7c197f63b9238d2";

    public static String token (String finger,String ip){

        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis()+EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String,Object> header = new HashMap<>();
            header.put("typ","JWT");
            header.put("alg","HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("finger",finger)
                    .withClaim("ip",ip)
                    .sign(algorithm);
        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }
        return token;
    }

    public static boolean verify(String token){
        /**
         * @desc   验证token，通过返回true
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return  false;
        }
    }
    public static void main(String[] args) {
        String username ="Xiaomi/renoir/renoir:11/RKQ1.201112.002/V12.5.3.0.RKICNXM:user/release-keys";
        String password = "168.135.456.424";
        String token = token(username,password);
        System.out.println(token);
        boolean b = verify("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmaW5nZXIiOiJYaWFvbWkvcmVub2lyL3Jlbm9pcjoxMS9SS1ExLjIwMTExMi4wMDIvVjEyLjUuMy4wLlJLSUNOWE06dXNlci9yZWxlYXNlLWtleXMiLCJpcCI6IjE2OC4xMzUuNDU2LjQyNCJ9.q9BHixjR8sNABdxVfYfBwJKo1oBfFcEETLpakcjvZDg");
        System.out.println(b);
    }
}